package cn.lxking.oauth2.server.configuration;

import cn.lxking.oauth2.server.domain.BasePermission;
import cn.lxking.oauth2.server.domain.BaseUser;
import cn.lxking.oauth2.server.service.BasePermissionService;
import cn.lxking.oauth2.server.service.BaseUserService;
import org.assertj.core.util.Lists;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
  @Resource private BaseUserService baseUserService;
  @Resource private BasePermissionService basePermissionService;

  @Override
  public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    BaseUser tbUser = baseUserService.getByUsername(s);
    List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
    if (tbUser != null) {
      // 声明用户授权
      List<BasePermission> tbPermissions = basePermissionService.selectByUserId(tbUser.getId());
      tbPermissions.forEach(
          tbPermission -> {
            GrantedAuthority grantedAuthority =
                new SimpleGrantedAuthority(tbPermission.getEnname());
            grantedAuthorities.add(grantedAuthority);
          });
      // 由框架完成认证工作
      return new User(tbUser.getUsername(), tbUser.getPassword(), grantedAuthorities);
    }
    return null;
  }
}
